package com.hyt.it.ogt.ks.mq;

import javax.annotation.Resource;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.hyt.it.ogt.ks.config.ConfigManager;
import com.hyt.it.ogt.ks.mq.model.CandidateInfoUpdateDTO;

import lombok.extern.slf4j.Slf4j;

/**
 * 修改考生信息
 *
 * @author 刘恒活
 * @since 2020/7/10 16:31
 */
@Component
@Slf4j
public class CandidateInfoProducer {
    @Resource
    private ConfigManager configManager;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 发布消息
     *
     * @param obj 消息体
     */
    public void sendMessage(CandidateInfoUpdateDTO obj) {
        this.sendMessage(obj, null);
    }

    /**
     * 发布消息
     *
     * @param obj        消息体
     * @param delayTimes 延迟消息，可以为空
     */
    public void sendMessage(CandidateInfoUpdateDTO obj, final Long delayTimes) {
        log.info("MQ队列初始化信息：【{}】，【{}】，【{}】", configManager.getDirect(), configManager.getCandidateUpdateQueue(),
                configManager.getCandidateUpdateRoute());
        obj.setServerIP(configManager.getServerIP());
        //给延迟队列发送消息
        rabbitTemplate.convertAndSend(configManager.getDirect(), configManager.getCandidateUpdateRoute(), JSON.toJSONString(obj),
                new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        if (delayTimes != null) {
                            //给消息设置延迟毫秒值
                            message.getMessageProperties().setExpiration(String.valueOf(delayTimes));
                        }
                        return message;
                    }
                });
        log.info("send json:{}", obj.toString());
    }
}
